package com.wlcb.jpower.chat.reply.handler.chain;

import com.wlcb.jpower.chat.reply.ReplyContext;
import com.wlcb.jpower.chat.reply.ReplyEntity;
import com.wlcb.jpower.chat.reply.ReplyHandler;
import com.wlcb.jpower.chat.service.customer.ChatService;
import com.wlcb.jpower.chat.service.customer.CustomerMsgService;
import com.wlcb.jpower.constant.ChatConfigConstant;
import com.wlcb.jpower.constant.ChatConstant;
import com.wlcb.jpower.constant.RedisEunm;
import com.wlcb.jpower.im.cache.ImChatRecordCache;
import com.wlcb.jpower.im.cache.SessionCache;
import com.wlcb.jpower.im.model.DataPacket;
import com.wlcb.jpower.module.common.utils.Fc;
import com.wlcb.jpower.module.common.utils.SpringUtil;
import com.wlcb.jpower.properties.JpowerChatProperties;
import com.wlcb.jpower.utils.RedisHelpUtils;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;

/**
 * @description: 转到客服
 * @author: liwenfei
 */
@Slf4j
public class CustomerReplyHandler extends ReplyHandler {

    private static CustomerMsgService customerMsgService;
    private static ChatService chatService;
    private static JpowerChatProperties properties;
    private final static String lockKey = "customerReplyHandler";


    static {
        properties = SpringUtil.getBean(JpowerChatProperties.class);
        customerMsgService = SpringUtil.getBean(CustomerMsgService.class);
        chatService = SpringUtil.getBean(ChatService.class);
    }

    @Override
    public ReplyEntity handler(DataPacket dataPacket, WxMpXmlMessage wxMessage) {
        if (!properties.getIsKefu()) {
            return this.getNextHandler().handler(dataPacket, wxMessage);
        }
        if (properties.getIsKeFuAppid() != null && properties.getIsKeFuAppid().length > 0 && !Fc.contains(properties.getIsKeFuAppid(), dataPacket.getAppId())) {
            return this.getNextHandler().handler(dataPacket, wxMessage);
        }

        if (ChatConstant.MessageTypeEnum.IMAGE.type.equals(dataPacket.getType())) {
            return this.getNextHandler().handler(dataPacket, wxMessage);
        }
        //加锁
        RedisHelpUtils.RedisLock redisLock = RedisHelpUtils.getRedisLock();
        boolean tryLock = redisLock.tryLock(lockKey);
        if (tryLock) {
            log.debug("进入------>人工客服");
            try {
                RedisHelpUtils.getRedisUtil().remove(RedisEunm.BAIDU_UNIT_SESSION.getKeyPrefix() + wxMessage.getFromUser());
                RedisHelpUtils.getRedisUtil().remove(RedisEunm.BAIDU_UNIT_SAY.getKeyPrefix() + wxMessage.getFromUser());

                //创建数据库会话
                String dialogId = customerMsgService.saveCustomerMsg(wxMessage.getFromUser(), dataPacket.getAppId());

                //创建redis会话
                ImChatRecordCache imChatRecordCache = ImChatRecordCache.getInstance(wxMessage.getFromUser(), dialogId)
                        .bindInit();
                dataPacket.setDialogId(imChatRecordCache.getDialogId());
                imChatRecordCache.setRecords(dataPacket);

                //根据消息类型 选择对应的处理器
                ReplyContext.MESSAGE_TYPE_MAP.get(dataPacket.getType()).handler(dataPacket, wxMessage, imChatRecordCache);

                //向其他客服广播待接入用户
                DataPacket wait = DataPacket.wait(chatService.getWaitUsers(), ChatConfigConstant.UserType.CUSTOMER);
                SessionCache.writeAll(wait);

                //封装提示消息返回给公众号用户
                String text = "您所发送的内容，公众号未能理解。已为您转接人工客服，请稍等！";
                ReplyEntity kefu = ReplyEntity.singleTextMessage(text, true).kefu();
                kefu.setAppId(dataPacket.getAppId());
                kefu.setToUser(wxMessage.getFromUser());
                return kefu;
            } catch (Exception e) {
                e.printStackTrace();
                return new ExceptionHandler(dataPacket.getAppId(), "客服", e).handler(dataPacket, wxMessage);
            } finally {
                redisLock.runlock(lockKey);
            }
        }
        return this.getNextHandler().handler(dataPacket, wxMessage);
    }

    @Override
    public ReplyEntity handler(DataPacket dataPacket, WxMpXmlMessage wxMessage, ImChatRecordCache cache) {
        return null;
    }
}
